package com.aaa.vegetablemarketexpress.service.impl;

import com.aaa.vegetablemarketexpress.dao.CartDao;
import com.aaa.vegetablemarketexpress.entity.Cart;
import com.aaa.vegetablemarketexpress.entity.Order;
import com.aaa.vegetablemarketexpress.entity.OrderItem;
import com.aaa.vegetablemarketexpress.dao.OrderDao;
import com.aaa.vegetablemarketexpress.service.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 购物车服务实现类
 */
@Service
public class CartServiceImpl implements CartService {

    @Resource
    private CartDao cartDao;
    /**
     * 添加商品到购物车
     *
     * @param cart 购物车对象
     * @return 是否添加成功
     */
    @Override
    public boolean addToCart(Cart cart) {
        // 检查是否已存在该用户的相同商品
        Cart existingCart = cartDao.selectByUserIdAndProductId(cart.getUserId(), cart.getProductId());

        if (existingCart != null) {
            // 如果已存在，则更新数量和金额
            existingCart.setQuantity(existingCart.getQuantity().add(cart.getQuantity()));
            existingCart.setAmount(existingCart.getAmount().add(cart.getAmount()));
            existingCart.setUpdateTime(new java.util.Date());
            return cartDao.updateById(existingCart) > 0;
        } else {
            // 如果不存在，则新增记录
            return cartDao.insert(cart) > 0;
        }
    }
    /**
     * 根据用户ID获取购物车详情
     *
     * @param userId 用户ID
     * @return 购物车详情列表
     */
    @Override
    public List<Cart> getCartDetailsByUserId(Long userId) {
        return cartDao.selectCartDetailsByUserId(userId);
    }
    /**
     * 根据购物车ID删除购物车商品
     *
     * @param cartId 购物车ID
     * @return 是否删除成功
     */
    @Override
    public boolean removeById(Long cartId) {
        return cartDao.deleteById(cartId) > 0;
    }
    /**
     * 更新购物车商品数量
     *
     * @param cartId  购物车ID
     * @param quantity 新数量
     * @return 是否更新成功
     */
    @Override
    public boolean updateQuantity(Long cartId, BigDecimal quantity) {
        Cart cart = cartDao.selectById(cartId);
        if (cart != null && quantity.compareTo(BigDecimal.ZERO) > 0) {
            // 获取商品单价
            BigDecimal unitPrice = cart.getAmount().divide(cart.getQuantity(), 2, BigDecimal.ROUND_HALF_UP);
            // 重新计算金额
            BigDecimal newAmount = unitPrice.multiply(quantity);

            cart.setQuantity(quantity);
            cart.setAmount(newAmount);
            cart.setUpdateTime(new java.util.Date());
            return cartDao.updateById(cart) > 0;
        }
        return false;
    }
    /**
     * 根据用户ID清空购物车
     * @param userId 用户ID
     * @return 是否删除成功
     */
    @Override
    public boolean clearCartByUserId(Long userId) {
        try {
            return cartDao.deleteByUserId(userId) > 0;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

}
